<template>
  <view class="container">
    <custom-status-bar></custom-status-bar>
	
	
	<uv-loading-page :loading="loading" loading-text="加载中..." font-size="24rpx"></uv-loading-page> 
	
	
    <!-- 顶部导航 -->
    <view class="header">
      <text class="greeting">{{ greeting() }}</text>
      <text class="username">
        <template v-if="username">
          {{ username }}
        </template>
        <template v-else>
          <text @click="gotoLogin">登录</text>
        </template>
      </text>
      <uni-search-bar class="search-input" @confirm="search" @input="handleSearch"
        cancel-button="none"></uni-search-bar>

    </view>

    <!-- 轮播广告 -->
    <view class="banner-section">
      <swiper :indicator-dots="true" :autoplay="true">
        <swiper-item v-for="banner in banners" :key="banner.pid">
          <image :src="banner.bannerImg" class="banner-image" @click="gotoDetail(banner.pid)" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 热卖推荐 -->
    <view class="recommend-section">
      <text class="section-title">热卖推荐</text>
      <view class="product-list">
        <view v-for="product in hotProducts" :key="product.id" @click="gotoDetail(product.pid)" class="product-item">
          <text class="hot-tag">hot</text>
          <image :src="product.image" class="product-image" />
          <view class="product-name">{{ product.name }}</view>
          <view class="product-english">{{ product.enname }}</view>
          <view class="product-price">￥{{ product.price }}</view>
        </view>
      </view>
    </view>


  </view>
</template>

<script setup>
import { ref, onMounted,onUnmounted, computed } from 'vue';
import { getBanner, accountInfo, getProductsByType } from "@/api/index.js"
import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
import { greeting } from "@/tools/index.js"


import { onLoad, onShow } from '@dcloudio/uni-app'

const banners = ref([])

const username = ref('')

const user_id = ref('')

const hotProducts = ref([])

const keyword = ref('')

const loading=ref(false)

// onShow(() => {
//   //用户信息
//   fetchUserInfo();
// });



onMounted(async () => {
 loading.value =true
  fetchUserInfo();
  //加载banner
  const res = await getBanner()
  //  console.log("banner:", res)
  banners.value = res.result
  // 加载热卖推荐产品
  const hots = await getProductsByType('isHot', 1)
  hotProducts.value = hots.result
  // console.log("热卖", hotProducts.value)
  
   loading.value =false
  // 监听登录和退出登录事件
    uni.$on('loginSuccess', fetchUserInfo)
    uni.$on('logoutSuccess', clearUserInfo)

})


// 页面卸载时移除事件监听
// onUnmounted(() => {
//   uni.$off('loginSuccess', fetchUserInfo)
//   uni.$off('logoutSuccess', clearUserInfo)
// })

// 清除用户信息
const clearUserInfo = () => {
  username.value = ''
  user_id.value = ''
}




const fetchUserInfo = async () => {
  try {
    // 首先尝试从本地存储获取用户信息
    const storedUserInfo = uni.getStorageSync('userInfo');
    if (storedUserInfo) {
      const userInfo = JSON.parse(storedUserInfo);
      username.value = userInfo.nickName;
      user_id.value = userInfo.userId;
      console.log("从本地存储获取用户信息成功");
    }

    // 然后从服务器获取最新的用户信息
    const token = uni.getStorageSync('coffee_token');
    if (token) {
      const res = await accountInfo(token);
      if (res.code === 'B001') {
        username.value = res.result[0].nickName;
        user_id.value = res.result[0].userId;
        // 更新本地存储的用户信息
        uni.setStorageSync('userInfo', JSON.stringify(res.result[0]));
        console.log("从服务器获取用户信息成功");
      }
    }else{
		// 如果没有token，清空用户信息
		      clearUserInfo();
	}
  } catch (e) {
    console.log("用户信息获取失败", e);

    // 如果从服务器获取失败，尝试从本地存储恢复
    try {
      const storedInfo = uni.getStorageSync('userInfo');
      if (storedInfo) {
        const userInfo = JSON.parse(storedInfo);
        username.value = userInfo.nickName;
        user_id.value = userInfo.userId;
        console.log("从本地存储恢复用户信息成功");
      }else{
		  // 如果本地也没有存储信息，清空用户信息
		          clearUserInfo();
	  }
    } catch (parseError) {
      console.log("解析本地存储的用户信息失败", parseError);
	  clearUserInfo();
    }
  }
}






const search = () => {
  // 跳转到搜索页
  uni.navigateTo({
    url: `/pages/search/search?query=${keyword.value}`,

  })
}


const gotoLogin = () => {
  uni.navigateTo({
    url: '/pages/protal/protal'
  })
}

const handleSearch = (event) => {
  console.log('搜索内容:', event);
  keyword.value = event
  // 实际开发中调用搜索接口
};


const gotoDetail = (pid) => {
  uni.navigateTo({ url: `/pages/detail/detail?pid=${pid}` });
};

</script>

<style scoped>
.container {
  padding: 20rpx;
  scrollbar-width: none;

}

/* 隐藏整个滚动条 */
.container::-webkit-scrollbar {
  display: none;
}

.header {
  display: flex;
  align-items: center;
  height: 100rpx;
  border-bottom: 1rpx solid #eee;
}

.greeting {
  margin-right: 10rpx;
}

.username {
  color: #007AFF;
  font-weight: bold;
}

.search-container {
  display: flex;
  align-items: center;
  background: #F5F5F5;
  border-radius: 40rpx;
  margin-left: auto;
  padding: 0 20rpx;
}

.search-input {
  margin-left: 10rpx;
  flex: 1;
}

.banner-section {
  margin-top: 20rpx;
}

.banner-image {
  width: 100%;
  height: 300rpx;
  border-radius: 20rpx;
}

.recommend-section {
  margin-top: 20rpx;
}

.section-title {
  background: #007AFF;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 40rpx;
  margin-bottom: 20rpx;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.product-item {
  width: 100%;
  /* 取消固定宽度 */
  text-align: center;
  position: relative;
  background: white;
  border-radius: 20rpx;
  padding: 20rpx;
}

.hot-tag {
  background: #007AFF;
  color: white;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  position: absolute;
  top: 20rpx;
  left: 20rpx;
}

.product-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 20rpx;
  margin: 20rpx auto;
}

.product-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
  text-align: left;
}

.product-english {
  text-align: left;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.product-price {
  text-align: left;
  color: #007AFF;
  font-weight: bold;
  font-size: 28rpx;
}


.tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-around;
  background: white;
  border-top: 1rpx solid #eee;
  padding: 20rpx 0;
}

.tab-icon {
  width: 50rpx;
  height: 50rpx;
  margin-bottom: 10rpx;
}
</style>